package com.stenio.fancat.service.baby;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stenio.fancat.common.errorCode.ErrorCode;
import com.stenio.fancat.domain.baby.BabyAccount;
import com.stenio.fancat.domain.baby.BabyIconImage;
import com.stenio.fancat.domain.baby.BabyPartner;
import com.stenio.fancat.domain.baby.BabyRelationship;
import com.stenio.fancat.domain.bo.BabyPartnerBO;
import com.stenio.fancat.domain.candy.Candy;
import com.stenio.fancat.domain.user.UserRelationship;
import com.stenio.fancat.domain.user.UserRelationshipFomId;
import com.stenio.fancat.domain.user.UserRelationshipName;
import com.stenio.fancat.exception.FanCatException;
import com.stenio.fancat.form.baby.BabyPartnerForm;
import com.stenio.fancat.mapper.baby.BabyAccountMapper;
import com.stenio.fancat.mapper.baby.BabyIconImageMapper;
import com.stenio.fancat.mapper.baby.BabyPartnerMapper;
import com.stenio.fancat.mapper.baby.BabyRelationshipMapper;
import com.stenio.fancat.mapper.candy.CandyMapper;
import com.stenio.fancat.mapper.user.*;
import com.stenio.fancat.service.wx.WxPushServiceQcl;
import com.stenio.fancat.util.DateUtil;
import com.stenio.fancat.util.EmptyUtil;
import com.stenio.fancat.util.RedisUtil;
import com.stenio.fancat.vo.BabyPartnerVO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * baby关系信息类
 */
@Service
public class BabyPartnerService extends ServiceImpl<BabyPartnerMapper, BabyPartner> {

    @Autowired
    private BabyPartnerMapper babyPartnerMapper;

    @Autowired
    private BabyAccountMapper babyMapper;

    @Autowired
    private BabyIconImageMapper babyIconImageMapper;

    @Autowired
    private UserRelationshipMapper userRelationshipMapper;

    @Autowired
    private UserRelationshipCandyMapper userRelationshipCandyMapper;

    @Autowired
    private UserRelationshipLogMapper userRelationshipLogMapper;

    @Autowired
    private BabyRelationshipMapper babyRelationshipMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private UserRelationshipNameMapper userRelationshipNameMapper;

    @Autowired
    private UserRelationshipFomIdMapper userRelationshipFomIdMapper;

    @Autowired
    private WxPushServiceQcl wxPushServiceQcl;

    @Autowired
    private CandyMapper candyMapper;

    @Value("${babyPartners}")
    private String babyPartnersKey;

    @Value("${babyPartnersNumbers}")
    private String babyPartnersNumbersKey;

    @Value("${babyPartnersList}")
    private String babyPartnersListKey;

    @Value("${key}")
    private String babyKey;

    @Value("${partnerList}")
    private String partnerListKey;

    @Value("${partnerBehaviorList}")
    private String partnerBehaviorListKey;

    @Value("templateNewPerson")
    private String templateNewPerson;

    /**
     * 查看宝宝伙伴
     * @param userId
     * @return
     */
    public List<BabyPartnerBO> selectPartners(String userId,String babyId) throws FanCatException {

        if(EmptyUtil.isEmpty(userId) || EmptyUtil.isEmpty(babyId)){
            throw new FanCatException("参数异常", ErrorCode.parameters);
        }

//        //判断Redis中是否含有key
//        if(EmptyUtil.isNotEmpty(redisUtil.get(babyPartnersKey+babyId))){
//            return (List<BabyPartnerBO>) redisUtil.get(babyPartnersKey+babyId);
//        }

        //创建容器
        List<BabyPartnerBO> list = new ArrayList<>();

        List<BabyRelationship> babyRelationship = babyRelationshipMapper.selectBabyByUid(userId);

        if(EmptyUtil.isEmpty(babyRelationship)){
            throw new FanCatException("请立即绑定宝宝", ErrorCode.addBaby);
        }

        //查看和宝宝关联的宝宝
        List<BabyPartner> partnersList = babyPartnerMapper.selectBabyPartnerByBid(babyId);

        if(partnersList.isEmpty()){
            throw new FanCatException("和任何baby没有关联",ErrorCode.norelationOfPartner);
        }

        partnersList.stream().forEach(partners -> {
            BabyAccount babyAccount = null;
            BabyIconImage babyIconImage =null;
                    BabyPartnerBO babyPartnerBO = new BabyPartnerBO();
            //封装基本信息
            if(!partners.getAssociatedBabyId().equals(babyId)){
                babyAccount = babyMapper.selectByBid(partners.getAssociatedBabyId());
            }else{
                babyAccount = babyMapper.selectByBid(partners.getBabyId());
            }

            babyPartnerBO.setBabyName(babyAccount.getNickName());
            babyPartnerBO.setBabyId(babyAccount.getBabyId());
            //封装宝宝头像--->URL
            if(!partners.getAssociatedBabyId().equals(babyId)){
                babyIconImage = babyIconImageMapper.selectByBid(partners.getAssociatedBabyId());
            }else{
                babyIconImage = babyIconImageMapper.selectByBid(partners.getBabyId());
            }
            babyPartnerBO.setBabyIconUrl(babyIconImage.getImage());

            list.add(babyPartnerBO);
        });

//        //存放Redis中
//        redisUtil.set(babyPartnersKey+babyId,list);

        return list;
    }


    /**
     * 根据userId查询小伙伴总数
     * @param userId
     * @return
     */
    public Integer selectCounts(String userId,String babyId) throws FanCatException {
        if(EmptyUtil.isEmpty(userId)){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }

        //判断Redis中是否含有key
        if(EmptyUtil.isNotEmpty(redisUtil.get(babyPartnersNumbersKey+babyId))){
            return (Integer) redisUtil.get(babyPartnersNumbersKey+babyId);
        }

        Integer number = 0;

        number = babyPartnerMapper.selectCountPartners(babyId);

        //存放Redis中
        redisUtil.set(babyPartnersNumbersKey+babyId,number);

        return number;
    }

    /**
     * 邀请小伙伴进入伙伴圈  相当于邀请一个新用户的业务逻辑  从baby注册开始实现  在baby注册成功后调用这个接口
     * @param babyPartnerForm
     * @return
     */
    @Transactional
    public Integer InvitePartner(BabyPartnerForm babyPartnerForm) throws FanCatException {
        if(EmptyUtil.isEmpty(babyPartnerForm)){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }

        BabyRelationship babyRelationship = babyRelationshipMapper.selectBabyByUidAndBid(babyPartnerForm.getUserId(),babyPartnerForm.getBabyId());
        if(EmptyUtil.isEmpty(babyRelationship)){
            throw new FanCatException("该用户没有创建baby",ErrorCode.addBaby);
        }
        List<BabyRelationship> list = babyRelationshipMapper.selectBabyByUid(babyPartnerForm.getAssociatedUserId());
        if(EmptyUtil.isEmpty(list)){
            throw new FanCatException("被邀请用户没有创建baby",ErrorCode.partnerNoBaby);
        }

        Integer number = 0;

        //1 查询两个user是否关联过
        BabyPartner babyPartner = null;
        for(int i = 0;i< list.size();i++){
            babyPartner = babyPartnerMapper.isInvitePartner(babyPartnerForm.getBabyId(),list.get(i).getBabyId());
            //2  已经建立了伙伴关系
            if(EmptyUtil.isNotEmpty(babyPartner)){
                throw new FanCatException("已经建立了伙伴关系",ErrorCode.hasrelationOfPartner);
            }

        }


        //建立关系  邀请当前user下所有的babyId
        Date date = new Date();
        for(int i = 0;i< list.size();i++){
            BabyPartner baby = new BabyPartner();
            if(!list.get(i).getBabyId().equals(babyRelationship.getBabyId())){
                baby.setAssociatedBabyId(list.get(i).getBabyId());
                baby.setBabyId(babyRelationship.getBabyId());
                baby.setCreateTime(date);
                baby.setUpdateTime(date);
                baby.setState(0);
                number = babyPartnerMapper.insert(baby);
            }
        }

        //邀请成功后推送微信模板消息
        String userId = babyPartnerForm.getUserId();
        UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(userId);
        String nickName = babyMapper.selectByBid(list.get(0).getBabyId()).getNickName();
        String[] arr = new String[5];
        if(list.size() == 1){
            arr[0] = nickName+"加入伙伴圈";
        }else {
            arr[0] = nickName+"等"+list.size()+"位宝宝加入伙伴圈";
        }
        arr[1] = "伙伴圈";
        arr[2] = DateUtil.format(date,"yyyy-MM-dd HH:mm:ss");
        UserRelationshipFomId userRelationshipFomId = userRelationshipFomIdMapper.selectFormIdByUid(userId);
        if(EmptyUtil.isNotEmpty(userRelationshipFomId)){
            String formId = userRelationshipFomIdMapper.selectFormIdByUid(userId).getFormId();
            //推送通知
            wxPushServiceQcl.pushOneUser(userRelationship.getOpenId(),formId,templateNewPerson,arr,babyPartnerForm.getPage());
            //修改这个formid的状态
            userRelationshipFomIdMapper.modifyFormIdByUid(userId,formId);
        }

        //操作Redis
        redisUtil.del(babyPartnerForm.getBabyId()+babyPartnersKey,babyPartnersNumbersKey+babyPartnerForm.getBabyId(),
                babyPartnersListKey+babyPartnerForm.getBabyId());
        //删除伙伴圈
        Set<String> keys = redisTemplate.keys(babyPartnerForm.getBabyId() + partnerListKey + "*");
        redisTemplate.delete(keys);
        //删除伙伴动态详情
        Set<String> parKeys = redisTemplate.keys(babyPartnerForm.getBabyId() +partnerBehaviorListKey +"*");
        redisTemplate.delete(parKeys);
        //删除宝宝伙伴列表
        redisUtil.del(babyPartnersKey+babyPartnerForm.getBabyId(),babyPartnersKey+babyPartnerForm.getBabyId());
        for(int i = 0;i< list.size();i++){
            redisUtil.del(list.get(i).getBabyId()+babyPartnersKey,babyPartnersNumbersKey+list.get(i).getBabyId(),
                    babyPartnersListKey+list.get(i).getBabyId());

            //删除伙伴圈
            Set<String> keysSec = redisTemplate.keys(list.get(i).getBabyId() + partnerListKey + "*");
            redisTemplate.delete(keysSec);
            //删除伙伴动态详情
            Set<String> parKeysSec = redisTemplate.keys(list.get(i).getBabyId() +partnerBehaviorListKey +"*");
            redisTemplate.delete(parKeysSec);
            //删除宝宝伙伴列表
            redisUtil.del(babyPartnersKey+list.get(i).getBabyId(),babyPartnersKey+list.get(i).getBabyId());
        }
        return number;
    }

    /**
     * 被邀请小伙伴的页面   --->   宝宝昵称  关系名称
     * @param userId
     * @return
     */
    public BabyPartnerVO invitedPage(String userId,String babyId) throws FanCatException {
        if(EmptyUtil.isEmpty(userId)){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }

        BabyPartnerVO babyPartnerVO = new BabyPartnerVO();
        //封装baby昵称
        BabyAccount babyAccount = babyMapper.selectByBid(babyId);
        babyPartnerVO.setNickName(babyAccount.getNickName());

        //封装关系名称
        BabyRelationship babyRelationship = babyRelationshipMapper.selectBabyByUidAndBid(userId,babyId);
        //UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(userId);
        UserRelationshipName userRelationshipName = userRelationshipNameMapper.selectName(babyRelationship.getRelationship());
        babyPartnerVO.setRelationshipName(userRelationshipName.getRelationshipName());

        //邀请金额为500  后期为请求出的数据
        babyPartnerVO.setCandy(500);

        return babyPartnerVO;
    }

    /**
     *  领糖果币（candy）  如果领完变成已领取
     * @param babyPartnerForm
     * @return
     */
    @Transactional
    public BabyPartnerBO getCandy(BabyPartnerForm babyPartnerForm) throws FanCatException {
        if(EmptyUtil.isEmpty(babyPartnerForm)){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }
        //查询该user关联的baby

        BabyPartnerBO babyPartnerBO = new BabyPartnerBO();
        //修改user的candyLog记录
        Integer candyFir = babyMapper.selectByBid(babyPartnerForm.getBabyId()).getSurplusCandy();
        //创建获取糖果币的示例
        Candy candy = candyMapper.selectCandy();
        userRelationshipLogMapper.modifyCandy(candy.getInviteBabyCandy(),babyPartnerForm.getUserId(),candyFir,babyPartnerForm.getBabyId());
        //修改user的candy
        userRelationshipCandyMapper.modifyCandy(candy.getInviteBabyCandy(),babyPartnerForm.getUserId(),babyPartnerForm.getBabyId());
        //修改宝宝的candy
        babyMapper.modifyCandy(candy.getInviteBabyCandy(),babyPartnerForm.getBabyId());
        //修改领取candy的状态为 1
        babyPartnerMapper.modifyState(babyPartnerForm.getBabyId(),babyPartnerForm.getAssociatedBabyId());

        BabyPartner babyPartner = babyPartnerMapper.isInvitePartner(babyPartnerForm.getBabyId(),babyPartnerForm.getAssociatedBabyId());
        babyPartnerBO.setState(babyPartner.getState());

        //操作Redis
        Set<String> keys = redisTemplate.keys(babyKey + babyPartnerForm.getBabyId() + "*");
        redisTemplate.delete(keys);
        redisUtil.del(babyPartnersListKey+babyPartnerForm.getBabyId());

        return babyPartnerBO;
    }


    /**
     * 已经邀请到的小伙伴  ---   展示出全部
     * @param userId
     * @return
     */
    public List<BabyPartnerBO> selectPartnersList(String userId,String babyId) throws FanCatException {
        if (EmptyUtil.isEmpty(userId)) {
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }

        //判断Redis中是否含有key
        if(null != redisUtil.get(babyPartnersListKey+babyId)){
            return (List<BabyPartnerBO>) redisUtil.get(babyPartnersListKey+babyId);
        }

        //创建容器
        List<BabyPartnerBO> list = new ArrayList<>();
        //查询baby关联的baby
        List<BabyPartner> babyPartnerList = babyPartnerMapper.selectBabyPartnerByBid2(babyId);
        if(babyPartnerList.isEmpty()){
            throw new FanCatException("该baby下没有邀请到任何伙伴",ErrorCode.norelationOfPartner);
        }
        babyPartnerList.stream().forEach(bp -> {
            BabyPartnerBO babyAccountVO = new BabyPartnerBO();
            BabyAccount babyAccount = babyMapper.selectByBid(bp.getAssociatedBabyId());
            BabyIconImage babyIconImage = babyIconImageMapper.selectByBid(bp.getAssociatedBabyId());
            babyAccountVO.setBabyId(babyAccount.getBabyId());
            babyAccountVO.setBabyName(babyAccount.getNickName());
            babyAccountVO.setBabyIconUrl(babyIconImage.getImage());
            babyAccountVO.setState(bp.getState()); //如果是1展示为已经领取
            list.add(babyAccountVO);
        });

        //存放Redis中
        redisUtil.set(babyPartnersListKey+babyId,list);

        return list;
    }

    /**
     * 分享判断两个user的关系
     * @param userId
     * @param associatedUserId
     * @return
     * @throws FanCatException
     */
    public Map<String,Object> judgeRelation(String userId,String associatedUserId,String babyId,String associatedBabyId) throws FanCatException {
        if (EmptyUtil.isEmpty(userId) ||EmptyUtil.isEmpty(associatedUserId)){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }

        Map<String,Object> map = new HashMap<>();

        Integer kinsfolkState = 0;
        Integer partnerState = 0;


        if(null == babyRelationshipMapper.selectBabyByUidAndBid(babyId,associatedUserId)){
            kinsfolkState = 0;
            map.put("kinsfolkState",kinsfolkState);
        }else{
            kinsfolkState = 1;
            map.put("kinsfolkState",kinsfolkState);
        }

        if(null == associatedBabyId){
            partnerState = 2;
            map.put("partnerState",partnerState);
        }else {
            BabyPartner babyPartner = babyPartnerMapper.isInvitePartner(babyId,associatedBabyId);
            if(null == babyPartner){
                partnerState = 0;
                map.put("partnerState",partnerState);
            }else{
                partnerState = 1;
                map.put("partnerState",partnerState);
            }
        }

        return map;
    }

}
